<template>
  <div>
    <div class="left-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="商品分类查询">
          <el-select v-model="formInline.value" placeholder="分类查询">
            <el-option
              :label="item"
              :value="item"
              v-for="item in showGoods"
              :key="item._id"
            ></el-option>
          </el-select>
          <el-button
            type="primary"
            style="margin-left: 10px"
            @click="onSubmitTag"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="搜索查询">
          <el-input
            v-model="formInlineFind.value"
            placeholder="搜索"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>

          <el-button type="button" @click="dialogFormVisible = true"
            >新增</el-button
          >
          <el-dialog title="新增商品" :visible.sync="dialogFormVisible" :before-close="handleClose">
            <!-- 新增上传图片 -->
             <el-upload
                action="/api/goods/upload"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            <el-form :model="form" ref="form" status-icon :rules="rules">
              <el-form-item label="商品名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form.name" autocomplete="off"></el-input>
              </el-form-item>
              <!-- <el-form-item label="商品图片" :label-width="formLabelWidth">
                <el-input v-model="form.pictures" autocomplete="off"></el-input>
              </el-form-item> -->
              <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
                <el-input v-model="form.price" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="商品描述" :label-width="formLabelWidth" prop="description">
                <el-input
                  v-model="form.description"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类" :label-width="formLabelWidth" prop="tag">
                <el-input v-model="form.tag" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="handle()">取 消</el-button>
              <el-button
                type="primary"
                @click=" handleAddGoods(form)"
                >确 定</el-button
              >
            </div>
          </el-dialog>

          <el-dialog title="修改商品" :visible.sync="dialogFormSee">
            <el-upload
              action="/api/goods/upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleAvatarSuccess"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
            <el-form :model="changeForm">
              <el-form-item
                label="商品名称"
                :label-width="changeFormLabelWidth"
              >
                <el-input
                  v-model="changeForm.name"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item label="商品图片" :label-width="formLabelWidth">
                <el-input v-model="form.pictures" autocomplete="off"></el-input>
              </el-form-item> -->
              <el-form-item
                label="商品价格"
                :label-width="changeFormLabelWidth"
              >
                <el-input
                  v-model.number="changeForm.price"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="商品描述"
                :label-width="changeFormLabelWidth"
              >
                <el-input
                  v-model="changeForm.description"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="商品分类"
                :label-width="changeFormLabelWidth"
              >
                <el-input
                  v-model="changeForm.tag"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormSee = false">取 消</el-button>
              <el-button
                type="primary"
                @click="(dialogFormSee = false), handleChangeGoods(changeForm)"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="goods" style="width: 100%">
      <el-table-column
        align="center"
        fixed
        prop="name"
        label="商品名称"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="pictures"
        label="商品图片"
      >
      <template slot-scope="scope">
        <!-- 后端的图片存放路径   每一排的图片 -->
        <el-image style="width:100px;height:70px" :src="'/api/images/'+scope.row.pictures" fit=""></el-image>
      </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="price"
        label="商品价格"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="description"
        label="商品描述"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="tag"
        label="商品分类"
      ></el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row), (dialogFormSee = true)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination background layout="prev, pager, next,total" 
      :page-size="limit"
      :current-page="page"
      :page-count="pagerCount"
      :total="total"
      @current-change="onPageChange"
      >
    </el-pagination>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      //上传图片
      dialogImageUrl: "",
      dialogVisible: false,
      //分类删选
      tag: [],
      showGoods: [], //删选下拉分类数组
      //下拉查询
      formInline: {
        type: "tag", //删选的是tag分类，这里给一个具体的删选值，只查询tag这一类
        value: "",
      },
      //模糊查询
      formInlineFind: {
        type: "",
        value: "", //查询输入框内容
      },
      data:[],//模糊查询数组
      //新增表单商品
      dialogFormVisible: false,
      form: {
        name: "",
        pictures:'',
        price: "",
        description: "",
        tag: "",
      },
      formLabelWidth: "80px",
      //修改商品
      dialogFormSee: false,
      changeForm: {
        id: "",
        name: "",
        pictures:'',
        price: "",
        description: "",
        tag: "",
      },
      changeFormLabelWidth: "80px",

      //表单验证规则
      rules:{
        name:[
           { required: true, message: '请输入商品名称', trigger: 'blur'},
        ],
        price: [
            { required: true, message: '请输入商品价格', trigger: 'blur'},
        ],
        description:[
          { required: true, message: '请输入商品描述', trigger: 'blur' },
        ],
        tag:[
          { required: true, message: '请输入商品分类', trigger: 'blur' },

        ]
      }
    };

  },
  methods: {
    //编辑
    handleEdit(index, row) {
      //修改回填信息
      this.changeForm = {
        id: row._id,
        name: row.name,
        pictures:row.pictures,
        price: row.price,
        description: row.description,
        tag: row.tag,
      };
    },
   
    handleChangeGoods(changeForm) {
      this.$store.dispatch("goodsStore/changeGoodsData", changeForm);
      this.$store.dispatch("goodsStore/getGoodsData");
    },
    //删除
    handleDelete(index, row) {
      this.$store.dispatch("goodsStore/deleteGoodsData", row._id); //这里的id传递仓库去
      this.$store.dispatch("goodsStore/getGoodsData"); //t
    },
    //新增事件
    handleAddGoods(form) {
      this.$store.dispatch("goodsStore/addGoodsData", form);
      this.handleClose();
      this.$store.dispatch("goodsStore/getGoodsData");
    },
    //分类查询
    onSubmitTag() {
      console.log(this.formInline);
      this.$store.dispatch("goodsStore/getInputGoods", this.formInline); //这里传的是对象到仓库
    },
    //模糊搜索查询
    onSubmit() {
      console.log(this.formInlineFind); //type,value
      if(this.formInlineFind.value!==""){
        let resp = this.data.filter((data)=>!this.formInlineFind.value||data.name.toLowerCase().includes(this.formInlineFind.value.toLowerCase())
        ||data.tag.toLowerCase().includes(this.formInlineFind.value.toLowerCase())
        ||data.price.toString().toLowerCase().includes(this.formInlineFind.value.toLowerCase())
        );//includes() 方法用于判断字符串是否包含指定的子字符串
        console.log(resp);
        this.$store.commit("goodsStore/setGoods",resp);//找到了显示查询的内容在表格
      }else{
        this.$store.dispatch("goodsStore/getGoodsData");//否则显示所有
      }
    },
    //上传图片
     handleAvatarSuccess(res) {
      console.log(res);
        // this.imageUrl = URL.createObjectURL(file.raw);
        this.form.pictures=res.data;//图片上传成功
    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },

      
    

    //移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //预览图片
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //清空表单
    handleClose(){
      console.log(this.$refs.form);
      this.$refs.form.resetFields();//表单重置方法
      this.dialogFormVisible = false;//关闭对话框
    },
    handle(){
      this.handleClose();
    },
    //分页
    onPageChange(page){//点击当前页
      this.$store.dispatch("goodsStore/getGoodsData",{
        page,
        pageSize:this.limit,
      });
    },

  },
  //查询全部
  computed: {
    ...mapState("goodsStore", ["goods", "isLoading","page","limit","pagerCount","total"]),
  },
  created() {
    //全部商品
    this.$store.dispatch("goodsStore/getGoodsData").then(() => {
      let map = new Map();
      //通过this.$store.state能拿到仓库里面的数据
      let resp = this.$store.state.goodsStore.goods.filter(
        (item) => !map.has(item.tag) && map.set(item.tag, 1)
      ); //删选去重
      console.log(resp);
      this.tag = resp;
      this.showGoods = this.tag.map((item) => item.tag); //遍历出tag分类
      console.log(this.showGoods);
      this.data=this.$store.state.goodsStore.goods;//模糊查询所有商品
    });

    this.$store.dispatch("goodsStore/getGoodsData");
  },
};
</script>

<style scoped>
.el-table-column {
  text-align: center;
}
.left-form {
  text-align: left !important;
}
</style>